<template>
  <my-window :title="title" :modal="modal" :wrapper-closable="true" :modal-append-to-body="modalAppendToBody"
    :visible.sync="visible" destroy-on-close embed size="100%" :width="width"
    drawer-body-style="padding:0px;height: calc(100% - 61px);" :before-close="onCancel">
    <my-container v-loading="pageLoading" style="height: 100%;">
      <!--查询-->
      <template #header>
        <el-form class="ad-form-query" :inline="true" @submit.native.prevent>
          <el-form-item>
            <el-upload class="upload-demo" action="" :on-change="handleChange" :on-remove="handleRemove"
              :show-file-list="false"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
              :auto-upload="false">
              <el-tooltip content="只能上传xls/xlsx 文件" placement="top-start">
                <el-button type="primary">选择文件</el-button>
              </el-tooltip>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onDownload">下载模板</el-button>
          </el-form-item>
        </el-form>
      </template>

      <!--列表-->
      <el-table v-loading="listLoading" :data="excelData" height="500" :border="true">
        <el-table-column v-for="(item,index) in columns" :prop="item.prop" :label="item.label" width />
      </el-table>
    </my-container>
    <template #footer>
      <el-button @click.native="onCancel">取消</el-button>
      <el-button type="primary" @click="onImport">导入</el-button>
    </template>
  </my-window>
</template>

<script>
  import MyContainer from '@/components/my-container'
  import MyWindow from '@/components/my-window'

  export default {
    name: 'MyImportWindow',
    components: {
      MyContainer,
      MyWindow,
    },
    props: {
      title: {
        type: String,
        default: '数据导入'
      },
      width: {
        type: String,
        default: '50%'
      },
      visible: {
        type: Boolean,
        default: false
      },
      form: {
        type: String,
        default: ''
      },
      multiple: {
        type: Boolean,
        default: false
      },
      modal: {
        type: Boolean,
        default: false
      },
      modalAppendToBody: {
        type: Boolean,
        default: false
      },
      columns: [],
      templateFileUrl: {
        type: String,
        default: ''
      },
    },
    data() {
      return {
        excelData: [], //存放数据的数组
        fileTemp: "", //导入函数需要的File内容
        pageLoading: false,
        listLoading: false,
      }
    },
    methods: {
      // 取消
      onCancel() {
        this.$emit('update:visible', false)
        this.$emit('cancel')
      },
      // 确定
      onImport() {
        if (this.excelData.length > 0) {
          this.pageLoading = true
          this.$emit('click', this.excelData, () => {
            this.excelData = []
            this.pageLoading = false
          })
        } else {
          this.$message({
            message: "无法导入空数据",
            type: 'error'
          })
        }
      },
      handleChange(file, list) {
        this.fileTemp = file.raw;
        if (this.fileTemp) {
          if (
            this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
            this.fileTemp.type == "application/vnd.ms-excel"
          ) {
            this.importfxx(this.fileTemp);
          } else {
            this.$message({
              type: "warning",
              message: "附件格式错误，请删除后重新上传！",
            });
            this.handleRemove();
          }
          if (list.length > 1 && file.status !== "fail") {
            list.splice(0, 1);
          }
        } else {
          this.$message({
            type: "warning",
            message: "请上传附件！",
          });
        }
      },

      handleRemove() {
        this.fileTemp = null;
      },
      // 导入函数
      importfxx(obj) {
        // let _this = this;
        // 通过DOM取文件数据
        var rABS = false; //是否将文件读取为二进制字符串
        var f = obj;
        var reader = new FileReader();
        const self = this;
        //if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function(f) {
          var binary = "";
          // var pt = this;
          var wb; //读取完成的数据
          var outdata;
          var reader = new FileReader();
          reader.onload = function(e) {
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i]);
            }
            var XLSX = require("xlsx");
            wb = XLSX.read(binary, {
              type: "binary",
            });
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是需要的那个数组
            //数据转换
            outdata.forEach(item => {
              var jsonData = {};
              self.columns.forEach(column => {
                jsonData[column.prop] = item[column.label];
              });
              self.excelData.push(jsonData);
            });
          };
          reader.readAsArrayBuffer(f);
        };
        if (rABS) {
          reader.readAsArrayBuffer(f);
        } else {
          reader.readAsBinaryString(f);
        }
      },
      // 下载模板
      onDownload() {
        window.open(this.templateFileUrl)
      },
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .el-dialog__body {
    padding: 0px;
  }
</style>
